AddCSLuaFile("shared.lua")
AddCSLuaFile("cl_init.lua")
AddCSLuaFile("cl_buildingsgui.lua")
AddCSLuaFile("cl_buildings.lua")
AddCSLuaFile("list.lua")
AddCSLuaFile("cl_ghost.lua")
AddCSLuaFile("cl_vote.lua")


include("shared.lua")
include("vote.lua")
include("upgradetree/init.lua")


concommand.Add("garc_spawn", function( ply, cmd, args )

	if #args != 1 /* || !ply:IsComm() */ then
		return
	end
	
	if (ply.LastCommand or 0) > CurTime() then
		return
	end
	
	ply.LastCommand = CurTime() + 0.5
	
	local Weapon = ply:GetActiveWeapon()
	
	if !IsValid( Weapon ) || Weapon:GetClass() != "garc_builder" then
		return
	end
	
	local Trace = BUILDING:PlayerTrace( ply )
	
	if !Trace.Hit then
		return
	end

	local EntId = tonumber( args[1] )
	local building = BUILDING:Get( EntId )
	
	if !building then
		return
	end
	
	local Team = ply:Team()
	
	//TODO: Check for resources
	
	local Ent = ents.Create( building.ent )
	
	BUILDING:UpdatePos( Trace , Ent, ply, building.YRotate )
	
	if !BUILDING:CanSpawn( Ent ) then
		Ent:Remove()
		return
	end
	
	Ent:SetPhysicsAttacker( ply )
	Ent:SetTeam( Team )
	Ent:Spawn()
	
	local ed = EffectData()
		ed:SetEntity( Ent )
	util.Effect( "propspawn", ed )

end )



hook.Add("StartGame", "StartCommTimer", function()

	hook.Add("Think", "CheckCommVote", function()
		if COMMVOTE:TimeLeft() < 0 then
			hook.Remove("Think", "CheckCommVote")
			COMMVOTE:ElectComm()
		end
	end )
	
end )

function COMMVOTE:CheckComms()

	if COMMVOTE:TimeLeft() < 0 then
		for _, v in pairs( team.GetValidTeams() ) do
			if team.GetComm( v ) then
				COMMVOTE:ElectCommTeam( v )
			end		
		end	
	end

end

hook.Add("PlayerRequestTeam", "CheckComms", function() timer.Simple(0.0, COMMVOTE.CheckComms ) end )
hook.Add("PlayerDisconnected", "CheckComms", function() timer.Simple(0.0, COMMVOTE.CheckComms ) end )
hook.Add("PlayerInitialSpawn", "CheckComms", function() timer.Simple(0.0, COMMVOTE.CheckComms ) end )